package com.example.apollotogit.utils;

import com.alibaba.fastjson.JSON;
import com.example.apollotogit.config.RedisClient;
import com.example.apollotogit.service.imp.HandleServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class Start implements ApplicationRunner {

    @Autowired
    private RedisClient redisClient;

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public void run(ApplicationArguments args) throws Exception {
        Map jsonCon = GetJsonUtil.getAddress();
        if(jsonCon.containsKey("start") && jsonCon.get("start").equals("1")) {
            String myKey = "APOLLOTOGITMQ";
            while (true) {
                Long size = redisClient.getSize(myKey);
                //监听到key值变化，判断key是否含有值
                if (size > 0) {
                    System.out.println("redis size = " + size + "-----" + dateFormat.format(new Date()));
                    for (Long i = size; i > 0; i--) {
                        String s = (String) redisClient.brpop(myKey, 0, TimeUnit.SECONDS);
                        Map map1 = (Map) JSON.parse(s);
                        //判断参数是否为空
                        if (!map1.isEmpty()) {
                            System.out.println("start solve");
                            //调用逻辑进行自动拉取
                            try {
                                HandleServiceImpl handleService = new HandleServiceImpl();
                                handleService.getPrintInfo(map1);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                } else {
                    Thread.sleep(20000);
                }
                System.gc();
            }
        }
    }
}
